
import { v4 as uuid } from 'uuid'
import tinymce from 'tinymce/tinymce'
import { refreshItemFootnoteNumbers } from './noteSettings'
import { getNumber, getAlphabetNumber, resetNotesSiblingsNumber } from '@/utils/exampleTag'
import { resetTableFootnoteNumbers } from '../table/noteSetting'
import store from '@/store'
import { checkBeforeInsert } from '@/utils/helpers'
import { Message } from 'element-ui'

tinymce.PluginManager.add('footnote', function (editor) {
  // 单击条文脚注时，弹窗修改脚注内容
  editor.on('click', (event) => {
    const node = event.target
    const classList = node.classList
    if (editor.dom.getParent(node, '.page_footnote')) {
      // 使光标停留在页脚的条文脚注旁边
      editor.selection.setCursorLocation(editor.dom.getParent(node, '.page_footnote'), 0)
      // 点击脚注，打开弹窗编辑
      return openDialog(node)
    }
    if (classList.contains('item_footnote') && classList.contains('in-body')) {
      const parent = editor.dom.getParent(node, 'p[data-type="paragraph"]')
      if (parent) {
        editor.selection.setCursorLocation(parent, 0)
      }
      // 点击脚注，打开弹窗编辑
      openDialog(node)
    }
  })

  // 删除条文脚注时，将页脚的脚注也删除，同时刷新现有的条文脚注的编号
  const observer = new MutationObserver(
    function (mutationsList, observer){
      for (let mutation of mutationsList) {
        const node = mutation.removedNodes?.[0]
        if (mutation.type === "childList") {
          if (node && node.nodeName === 'SPAN') {
            const classList = node.classList
            if (classList?.contains?.('table_footnote')) {
              // 删除了表脚注，刷新表脚注的编号
              resetTableFootnoteNumbers(editor.dom.getParent(editor.selection.getNode(), 'table'), editor)
            } else if (classList?.contains?.('item_footnote')){
              // 删除了条文脚注，刷新条文脚注的编号
              refreshItemFootnoteNumbers(editor)
            }
          } else if (node && node.nodeName === 'P' && node.dataset.type === 'table_footnote') {
            // 删除了表脚单元行中的表脚注，同步删除表格正文中的标记
            const tableDom = editor.dom.getParent(editor.selection.getNode(), 'table')
            if (tableDom) {
              console.log('删除脚注-')
              const span = tableDom.querySelector(`tbody span.table_footnote[data-id="${node.dataset.referredId}"]`)
              const p = tableDom.querySelector(`tfoot p.table_footnote[data-referred-id="${node.dataset.referredId}"]`)
              editor.undoManager.ignore(function () {
                editor.dom.remove(span)
                editor.dom.remove(p)
              })
              // 刷新表脚注的编号
              resetTableFootnoteNumbers(tableDom, editor)
            }
          }
        }
      }
    }
  )
  editor.on('init', function() {
    observer.observe(editor.getDoc(), { attributes: true, childList: true, subtree: true })
  })

  // 自动刷新图脚注的编号
  editor.on('keyup', (event) => {
    const node = editor.selection.getNode()
    const prevNode = node?.previousSibling
    const _classMatch = prevNode?.classList?.contains?.('figure_footnote')
    if (_classMatch && "Enter" === event.key) {
      console.log('---PluginManager footnote keyup Enter---')
      // 从图脚注所在行按住enter，下一行的编号+1
      const number = getNumber({
        node, 
        classList: ['figure_footnote'], 
        sortType: 0,
        dataLang: prevNode.dataset.lang
      })
      editor.dom.setAttribs(node, {
        class: prevNode.className,
        'data-number': number,
        'data-type': prevNode.dataset.type,
        'data-lang': prevNode.dataset.lang
      })
      // 重置紧邻的连续编号
      resetNotesSiblingsNumber({
        node,
        editor,
        classList: ['figure_footnote'], 
        dataLang: node.dataset.lang,
        sortType: 0
      })
    }
    if (event.key === 'Delete' || event.key === 'Backspace') {
      // 删除之后刷新后续的编号
      const _classMatch = node?.classList?.contains?.('figure_footnote')
      if (_classMatch) {
        console.log('---PluginManager footnote keyup ' + event.key + '-------')
        resetNotesSiblingsNumber({
          node, 
          editor,
          classList: ['figure_footnote'], 
          dataLang: node.dataset.lang,
          sortType: 0
        })
      }
    }
  })

  // 添加修改图脚注
  editor.addCommand('toggleImgFootnote', (ui, value) => {
    const node = editor.selection.getNode()
    // 只能在图片、图注之后插入图脚注
    const parent = editor.dom.getParent(node, '.data-content-image-wrapper')
    const img = parent?.querySelector?.('.image-wrapper')
    if (!img || editor.dom.nodeIndex(img) > editor.dom.nodeIndex(node)) {
      return Message.warning({
        message: `请在图结构化块内容中添加图脚注`,
        showClose: true
      })
    }
    const { dataLang } = value
    let number = 'a'
    // 图脚注只能存在于图片和图题之间，如果有图注，则图脚注在图注之后, 中文在前，英文在后
    if (node.dataset.type === 'figure_footnote' && node.dataset.lang === dataLang) {
      // 在图脚注的节点插入
      number = getAlphabetNumber(node.dataset.number)
      return insertImageFootnoteAfterNode(node, number, dataLang)
    }
    // 在图结构化块的其他地方插入图脚注
    const footnotes = parent.querySelectorAll('.figure_footnote.' + dataLang)
    if (footnotes?.length > 0) {
      // 当前图结构化块已经存在图脚注，则在最后一个图脚注后面插入新的图脚注
      const lastFootnote = footnotes[footnotes.length - 1]
      if (lastFootnote.dataset.lang === dataLang) {
        number = getAlphabetNumber(lastFootnote.dataset.number)
        return insertImageFootnoteAfterNode(lastFootnote, number, dataLang)
      }
    }
    if (dataLang === 'en') {
      const footnotes = parent.querySelectorAll('.figure_footnote.zh')
      if (footnotes?.length > 0) {
        // 英文图脚注加在中文的后面
        const lastFootnote = footnotes[footnotes.length - 1]
        console.log('英文图脚注加在中文图脚注的后面')
        number = 'a'
        return insertImageFootnoteAfterNode(lastFootnote, number, dataLang)
      }
    }
    const notes = parent.querySelectorAll('.figure_note')
    if (notes?.length > 0) {
      // 当前图结构化块不存在图脚注但存在图注，则在最后一个图注后面插入新的图脚注
      return insertImageFootnoteAfterNode(notes[notes.length - 1], number, dataLang)
    }
    // 当前图结构化块不存在图脚注和图注，则在图片后面插入图脚注
    return insertImageFootnoteAfterNode(img, number, dataLang)
  })

  // 在指定的node后面插入图脚注
  function insertImageFootnoteAfterNode(referenceNode, number, dataLang) {
    const content = editor.dom.create('p', {
      'data-type': 'figure_footnote',
      'class': 'figure_footnote ' + dataLang,
      'data-id': uuid(),
      'data-note-id': uuid(),
      'data-number': number,
      'data-lang': dataLang
    }, '<br>')
    editor.dom.insertAfter(content, referenceNode)
    editor.selection.setCursorLocation(content, 0)
  }

  // 添加修改条文脚注
  editor.addCommand('toggleFootnote', () => {
    if (!checkBeforeInsert('item_footnote')) return
    const node = editor.selection.getNode()
    if ( node.contentEditable === 'false' || ['noneditable', 'irremovable'].some(i => node.classList.contains(i))) {
      return Message.warning({
        message: `条文脚注只能用于可修改的正文段落中`,
        showClose: true
      })
    }
    if ( (node.dataset?.type !== 'paragraph' && !editor.dom.getParent(node, 'p[data-type="paragraph"]'))
      || editor.dom.getParent(node, 'table')
    ) {
      return Message.warning({
        message: `条文脚注只能用于正文段落中！`,
        showClose: true
      })
    }
    openDialog()
  })

  const openDialog = function (node, _type) {
    let contentZh = ''
    let contentEn = ''
    const classList = node?.classList || null
    let referredId = ''
    if (node) {
      // 点击脚注进行修改
      if (classList?.contains?.('in-footer')) {
        // 点击的是页脚的脚注内容
        referredId = node.getAttribute('data-referred-id')
        if (node.dataset.lang === 'zh') {
          contentZh = node.textContent
        }
        if (node.dataset.lang === 'en') {
          contentEn = node.textContent
        }
      } else if (classList?.contains?.('in-body')){
        // 点击的是正文里面的条文脚注标记
        contentZh = node?.dataset?.contentZh || ''
        contentEn = node?.dataset?.contentEn || ''
        referredId = node.dataset?.id
      }
    }
    const inputZh = {
      type: "input",
      name: "contentZh",
      label: "中文",
      placeholder: '请输入',
      maxlength: 50
    }
    const inputEn = {
      type: "input",
      name: "contentEn",
      label: "英文",
      placeholder: '请输入',
      maxlength: 50
    }
    let inputItems = []    
    const languageType = store.getters.languageType
    let initData = {}
    if (!node) {
      // 新增
      inputItems.push(inputZh)
      if (languageType === 'both') {
        inputItems.push(inputEn)
      }
    } else {
      // 修改
      if (contentZh) {
        inputItems.push(inputZh)
        initData.contentZh = contentZh
      }
      if (contentEn) {
        inputItems.push(inputEn)
        initData.contentEn = contentEn
      }
    }
    return editor.windowManager.open({
      title: `请输入条文脚注内容`,
      size: 'normal',
      body: {
        type: "panel",
        items: inputItems
      },
      buttons: [
        {
          type: 'cancel',
          name: 'cancel',
          text: '取消'
        },
        {
          type: 'submit',
          name: 'save',
          text: '确定',
          primary: true
        }
      ],
      initialData: initData,
      onSubmit: function (e) {
        const data = e.getData()
        if (!node && (!data.contentZh?.trim() || (languageType === 'both' && !data.contentEn?.trim()))) {
          return Message.warning('条文脚注内容不能为空')
        }
        if (node) {
          const dataLang = node.dataset.lang
          if (dataLang === 'zh' && !data.contentZh?.trim() || 
            (dataLang === 'en' && !data.contentEn?.trim())
          ) {
            return Message.warning('条文脚注内容不能为空')
          }
        }
        e.close()
        addFootnote({
          contentZh: data.contentZh,
          contentEn: data.contentEn, 
          referredId
        })
      }
    })
  }

  // 添加条文脚注到页面中
  const addFootnote = function ({ contentZh, contentEn, referredId }) {
    if (!referredId) {
      // 新增条文脚注
      const dataId = uuid()
      // 添加条文脚注在正文中的标记
      editor.insertContent(`<span 
          class="item_footnote in-body"
          data-content-zh="${contentZh}"
          data-content-en="${contentEn || ''}"
          title="${contentZh}"
          data-type="footnote"
          data-id="${dataId}"
          contenteditable="false"
          data-number="1"
        >&#8203;</span>`)
      setTimeout(() => {
        // 刷新条文脚注的编号
        refreshItemFootnoteNumbers(editor)
      }, 100)
    }
    else {
      // 编辑条文脚注
      const node = editor.getDoc().querySelector(`span.item_footnote.in-body[data-id="${referredId}"]`)
      if (node) {
        editor.dom.setAttribs(node, {
          'data-content-zh': contentZh || node.dataset.contentZh,
          'data-content-en': contentEn || node.dataset.contentEn,
          'title': contentZh || node.dataset.contentZh
        })
      }
      if (contentZh) {
        const fnode = editor.getDoc().querySelector(`p.item_footnote.zh.in-footer[data-referred-id="${referredId}"]`)
        if (fnode) {
          fnode.textContent = contentZh
        }
      }
      if (contentEn) {
        const fnode = editor.getDoc().querySelector(`p.item_footnote.en.in-footer[data-referred-id="${referredId}"]`)
        if (fnode) {
          fnode.textContent = contentEn
        }
      }
    }
  }

  // 添加表脚注到页面中
  const addTableFootnote = function () {
    if (!checkBeforeInsert('table_footnote')) return
    const node = editor.selection.getNode()
    // 表脚注只能在表格正文中添加
    const ancestor = editor.dom.getParent(node, 'tbody')
    if (!ancestor) {
      return editor.windowManager.alert("请在表格正文中添加表脚注")
    }
    editor.execCommand('mceInsertTableFootRow', false, { act: 'table_footnote' })
  }

  const iconStr = `
  <svg width="24" height="25" viewBox="0 0 24 25" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
      <g transform="translate(-1526.000000, -161.000000)" fill="#000000" fill-rule="nonzero">
          <g id="tool" transform="translate(16.000000, 149.500000)">
              <g id="编组-2" transform="translate(190.000000, 8.000000)">
                  <g id="脚注" transform="translate(1320.000000, 3.500000)">
                      <rect id="矩形" opacity="0" x="0" y="0.5" width="24" height="24"></rect>
                      <path d="M8.54883998,19.4124985 C7.9781305,19.8558595 7.42628744,20.1891665 6.89331082,20.410847 C6.3619064,20.6325275 5.76289727,20.7441539 5.10100005,20.7441539 C4.49570212,20.7441539 3.9642977,20.6246665 3.50521459,20.3841196 C3.04770368,20.146717 2.69395814,19.8228433 2.44712235,19.4124985 C2.20028657,19.0037258 2.07608258,18.5603647 2.07608258,18.0824152 C2.07608258,17.4378122 2.2804689,16.8875414 2.69081373,16.4331749 C3.09958636,15.9772361 3.65929043,15.6722289 4.37464253,15.5165808 C4.52557396,15.4819924 4.89661374,15.4049545 5.48933405,15.2838949 C6.08205437,15.1628353 6.58987575,15.0527811 7.01437041,14.950588 C7.43729286,14.8515392 7.89794817,14.7273352 8.39161973,14.5842648 C8.36489229,13.9632448 8.2391161,13.5073061 8.01900776,13.2148765 C7.79575501,12.924019 7.33667191,12.7809486 6.64018623,12.7809486 C6.0411771,12.7809486 5.58995501,12.8642753 5.28966434,13.0293566 C4.98780148,13.1960101 4.72838808,13.4475624 4.51142414,13.7824416 C4.29446021,14.1157485 4.14510098,14.337429 4.05391324,14.4427666 C3.9642977,14.5496763 3.772489,14.6031312 3.48005935,14.6031312 C3.21435714,14.6031312 2.98638779,14.5182323 2.79300689,14.3484344 C2.59805379,14.1770644 2.50214944,13.9601004 2.50214944,13.6943982 C2.50214944,13.2793368 2.64993647,12.876853 2.94236612,12.4853746 C3.23794018,12.0938961 3.69545108,11.7715947 4.31489884,11.5184701 C4.937491,11.2653455 5.7125868,11.1379971 6.64018623,11.1379971 C7.67783983,11.1379971 8.49224069,11.2606289 9.08496101,11.5043202 C9.67925352,11.7495838 10.0990316,12.1363456 10.3427229,12.6661778 C10.5864143,13.1960101 10.7090461,13.8987845 10.7090461,14.7745013 C10.7090461,15.3279165 10.7074739,15.7964329 10.7059017,16.1831947 C10.7027573,16.5683843 10.6964685,16.9975955 10.6917519,17.4708285 C10.6917519,17.9126173 10.7640732,18.3748448 10.9118602,18.8559388 C11.0596473,19.3370327 11.1319686,19.6467566 11.1319686,19.7851104 C11.1319686,20.0256574 11.01877,20.2473379 10.7908006,20.4470076 C10.5628313,20.6451052 10.3049901,20.7441539 10.017277,20.7441539 C9.77515787,20.7441539 9.5361831,20.6293831 9.30035274,20.402986 C9.06452237,20.1750166 8.81296999,19.8448541 8.54883998,19.4124985 L8.54883998,19.4124985 Z M8.39319194,15.999247 C8.0473074,16.1265954 7.54577483,16.2618048 6.88544981,16.4017308 C6.22669699,16.543229 5.77075829,16.6469944 5.51606149,16.7130269 C5.26450911,16.7790594 5.02238993,16.9095522 4.79127617,17.1013609 C4.56173462,17.2947418 4.44539164,17.5635884 4.44539164,17.9094729 C4.44539164,18.2663629 4.58060105,18.5713702 4.85259207,18.8213503 C5.12301089,19.0713305 5.47518423,19.1971067 5.91540091,19.1971067 C6.38234503,19.1971067 6.81155629,19.0949136 7.2046069,18.8905272 C7.60080191,18.6861409 7.89008716,18.4220109 8.07403484,18.0997094 C8.28785437,17.7428195 8.39319194,17.1548158 8.39319194,16.3388427 L8.39319194,15.999247 L8.39319194,15.999247 Z" id="形状"></path>
                      <path d="M15.5053512,6.17764156 L15.773107,11.9404082 C15.8871387,11.819188 16.0143496,11.700402 16.1549711,11.5841217 C16.8198203,11.0421252 17.5857595,10.7707813 18.4530365,10.7707813 C19.5155683,10.7707813 20.4255644,11.2142943 21.1783824,12.111885 C21.9128814,12.9876338 22.286695,14.1229189 22.286695,15.5230677 C22.286695,17.0151097 21.8101157,18.2916915 20.8602702,19.3541113 C19.9044871,20.4231724 18.6490927,20.9618014 17.0902368,20.9618014 C16.3109984,20.9618014 15.545697,20.8077519 14.7944889,20.4988439 C14.4053163,20.3388103 14.1150811,20.1764434 13.9206587,20.0165446 C13.6623759,19.8041251 13.5594227,19.5856028 13.5594227,19.3792862 L13.5594227,8.70906921 C13.5594227,8.38665463 13.5285921,8.15076304 13.4385881,8.01294439 C13.361082,7.89426319 13.1584868,7.87892426 12.9008896,7.87892426 C12.9998035,7.031509 13.6249677,6.79308576 14.2398794,6.58175467 C15.1021391,6.27964735 15.4551148,6.17764156 15.5053512,6.17764156 Z M17.5747878,12.5932018 C17.1423421,12.5932018 16.7200226,12.7282795 16.3063284,12.9929221 C15.9350952,13.2304021 15.7351616,13.527418 15.7351616,13.8978029 L15.9001112,19.3158521 C16.0081504,19.4190434 16.1595462,19.4984137 16.3500622,19.5605384 C16.7849588,19.7023525 17.1660967,19.7753542 17.4940293,19.7753542 C18.3383342,19.7753542 18.9697478,19.4659036 19.3784083,18.8302094 C19.808724,18.1608295 20.0201028,17.350387 20.0201028,16.4013164 C20.0201028,15.4388667 19.8173378,14.5488584 19.4103462,13.731645 C19.2213376,13.3521277 18.976058,13.0649769 18.6695576,12.8749166 C18.3632023,12.6849462 17.9976097,12.5932018 17.5747878,12.5932018 Z" id="形状" stroke="#000000" stroke-width="0.5"></path>
                      <path d="M21.4375,2.10640727 L22.34375,2.10640727 L22.34375,8.57515727 L21.25,8.57515727 L21.25,4.01265727 C20.75,4.42932393 20.1770833,4.73140727 19.53125,4.91890727 L19.53125,3.79390727 C20.5104167,3.3772406 21.1458333,2.8147406 21.4375,2.10640727 Z" id="路径"></path>
                  </g>
              </g>
          </g>
      </g>
  </g>
</svg>
`
  editor.ui.registry.addIcon('footnoteIcon', iconStr);
  return (
    editor.ui.registry.addMenuButton('footnote', {
      tooltip: '脚注',
      icon: 'footnoteIcon',
      fetch: function (callback) {
        callback([
          {
            type: 'menuitem',
            text: '条文脚注',
            onAction: function () {
              if (!checkBeforeInsert('item_footnote')) return
              editor.execCommand('toggleFootnote', false, { action: 'footnote' })
            }
          },
          {
            type: 'menuitem',
            text: '表脚注',
            onAction: addTableFootnote,
          },
          {
            type: 'menuitem',
            text: '图脚注',
            onAction: function () {
              if (!checkBeforeInsert('figure_footnote')) return
              editor.execCommand('toggleImgFootnote', false, { action: 'figure_footnote', dataLang: 'zh' })
            }
          }
        ])
      }
    }),
    {
      getMetadata: function () {
        return {
          name: '脚注',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})
